package com.mango.lucene.demo.util;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class LuceneUtil {
	//更新索引，没有就创建
	public static void updateIndex() throws IOException{
		String indexPath = "tmp/testindex";
		File file = new File(indexPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String indexSufix = "/segments.gen";
        // 根据索引文件segments.gen是否存在判断是否是第一次创建索引
        File indexFile = new File(indexPath + indexSufix);
        if(indexFile.exists()){
        	System.out.println("索引已存在！");
        	return ;
        }
		//Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_9);
		Analyzer analyzer = new IKAnalyzer();

		// Store theindex in memory:
		// 索引存到内存中的目录
		//Directory directory = new RAMDirectory();
		// To store anindex on disk, use this instead:
		Directory directory = FSDirectory.open(file);
		// 配置索引
		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9,analyzer);
		if (IndexWriter.isLocked(directory)) {
			IndexWriter.unlock(directory);
		}
		IndexWriter iwriter = new IndexWriter(directory, config);
		//从数据库中读取信息进行索引 
		//select a.title,b.content from cms_article a left outer join cms_article_data b on a.id=b.id
		String sql = "select a.id,a.title,b.content from cms_article a left outer join cms_article_data b on a.id=b.id";
		List<Record> list = Db.find(sql);
		for(Record r:list){
			String id = r.getStr("id");
			String title = r.getStr("title");
			String content = r.getStr("content");
			Document doc = new Document();
			if(content == null){
				content = "";
			}
			doc.add(new Field("id", id,TextField.TYPE_STORED));
			doc.add(new Field("title", title,TextField.TYPE_STORED));
			doc.add(new Field("content",content,TextField.TYPE_STORED));
			iwriter.addDocument(doc);
		}
		System.out.println("索引建立成功，共"+list.size()+"条");
		iwriter.close();
	}
}
